import React from 'react'
import {
    View, StyleSheet, Image, TouchableWithoutFeedback, findNodeHandle, UIManager
} from 'react-native'

const maxWidth = 220
const maxHeight = 200

export default class CommunityMediaCell extends React.PureComponent {

    render() {
        let dic = this.props.data.img[0]
        this.pic = {
            uri: dic.url
        }
        if (dic.width == 0 || dic.height == 0) return null
        var width, height = 0
        if (dic.width / dic.height > maxWidth / maxHeight) {
            width = maxWidth
            height = dic.height / dic.width * width
        } else {
            height = maxHeight
            width = dic.width / dic.height * height
        }
        return (
            <TouchableWithoutFeedback onPress={this.onPress}>
                <View style={styles.container}>
                    <Image
                        ref='img'
                        style={[styles.img, { width: width, height: height }]}
                        source={this.pic}
                        cache={'force-cache'}
                    />
                </View>
            </TouchableWithoutFeedback>
        )
    }

    onPress = () => {
        const handle = findNodeHandle(this.refs.img)
        UIManager.measureInWindow(handle, (x, y, width, height) => {
            let frame = '{{' + x + ', ' + y + '}, {' + width + ', ' + height + '}}'
            var dict = JSON.parse(JSON.stringify(this.props.data.img[0]))
            dict.frame = frame
            dict.idx = 0
            this.props.clickImgAction(this.props.data, [dict], styles.img.borderRadius, 0)
        })
    }
}

const styles = StyleSheet.create({
    container: {
        marginLeft: 10,
        marginRight: 10,
        marginBottom: 5,
        marginTop: 5,
    },
    img: {
        borderRadius: 5,
        backgroundColor: '#eeeeee'
    },
})